package cxydmmszl.chapter02.t023;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

/**
 * <li style="color: red;">Prob</li>
 * 将单链表的每 K 个节点之间逆序
 * <li style="color: green;">Desc</li>
 * 给定一个单链表，实现一个调整单链表的函数，使得每 K 个节点之间的值逆序，
 * 如果最后不够 K 个节点一组，则不调整最后几个节点。
 * <li style="color: green;">Input</li>
 * 第一行一个整数 n，n 表示单链表的节点数量。
 * 第二行 n 个整数 val 表示链表的各个节点的值。
 * 第三行一个整数 K。
 * <li style="color: green;">Output</li>
 * 在给定的函数内返回链表的头指针。
 * <li style="color: blue;">Link</li> CD119
 *
 * @author habitplus
 * @since 2021-09-10 12:17
 */
public class Main {
    private static final StreamTokenizer st =
            new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    private static int nextInt() {
        try {
            st.nextToken();
            return (int) st.nval;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static class Node {
        int val;
        Node next;
        public Node(int val) {
            this.val = val;
        }
    }

    private static Node readAndGenList(int n) {
        Node tou = new Node(0), pre = tou, node;
        int num;
        for (int i = 0; i < n; i++) {
            num = nextInt();
            node = new Node(num);
            pre.next = node;
            pre = node;
        }

        return tou.next;
    }

    private static void printLinkedList(Node head) {
        StringBuilder sb = new StringBuilder();
        while (head != null) {
            sb.append(head.val).append(" ");
            head = head.next;
        }
        System.out.println(sb.toString());
    }

    public static Node reverseKNodes(Node head, int k) {
        if (head == null || k < 2) {
            return head;
        }

        int cnt = 0;
        Node tou = new Node(0);
        tou.next = head;
        Node pre = tou, nxt, tail;

        while (head != null) {
            cnt++;
            nxt = head.next;
            if (cnt % k == 0) {
                // 断开前 k 个节点
                head.next = null;
                // 翻转链表
                tail = pre.next;
                head = reverseList(tail);
                tail.next = nxt;
                pre.next = head;
                pre = tail;
            }
            head = nxt;
        }

        return tou.next;
    }

    private static Node reverseList(Node head) {
        Node pre = null;
        Node next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        int n = nextInt();
        Node head = readAndGenList(n);
        int k = nextInt();
        head = reverseKNodes(head, k);
        printLinkedList(head);
    }
}
